package com.example.myapplication

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.example.myapplication.utils.PermissionHelper
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*

class DataExportActivity : AppCompatActivity() {
    
    private lateinit var databaseHelper: DatabaseHelper
    private lateinit var spinnerDataType: Spinner
    private lateinit var editTextStartDate: EditText
    private lateinit var editTextEndDate: EditText
    private lateinit var buttonExport: Button
    
    companion object {
        private const val PERMISSION_REQUEST_CODE = PermissionHelper.STORAGE_PERMISSION_REQUEST_CODE
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data_export)
        
        databaseHelper = DatabaseHelper(this)
        
        // 初始化UI组件
        spinnerDataType = findViewById(R.id.spinnerDataType)
        editTextStartDate = findViewById(R.id.editTextStartDate)
        editTextEndDate = findViewById(R.id.editTextEndDate)
        buttonExport = findViewById(R.id.buttonExport)
        
        // 设置数据类型选择器
        setupDataTypeSpinner()
        
        // 设置日期选择器
        setupDatePickers()
        
        // 设置导出按钮
        buttonExport.setOnClickListener {
            exportData()
        }
        
        // 设置返回按钮
        // buttonBack.setOnClickListener {
        //     finish()
        // }
        
        // 设置默认日期范围（最近30天）
        val calendar = Calendar.getInstance()
        val endDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.time)
        
        calendar.add(Calendar.DAY_OF_MONTH, -30)
        val startDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.time)
        
        editTextStartDate.setText(startDate)
        editTextEndDate.setText(endDate)
    }
    
    private fun setupDataTypeSpinner() {
        val dataTypes = arrayOf("所有数据", "患者数据", "用户数据", "科室数据")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, dataTypes)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerDataType.adapter = adapter
    }
    
    private fun setupDatePickers() {
        editTextStartDate.setOnClickListener {
            showDatePicker(editTextStartDate)
        }
        
        editTextEndDate.setOnClickListener {
            showDatePicker(editTextEndDate)
        }
    }
    
    private fun showDatePicker(editText: EditText) {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        
        val datePickerDialog = android.app.DatePickerDialog(
            this,
            { _, selectedYear, selectedMonth, selectedDay ->
                val date = String.format(java.util.Locale.ROOT, "%04d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDay)
                editText.setText(date)
            },
            year, month, day
        )
        datePickerDialog.show()
    }
    
    private fun exportData() {
        // 检查权限
        if (!PermissionHelper.checkStoragePermission(this)) {
            PermissionHelper.requestStoragePermission(this)
            return
        }
        
        val dataType = spinnerDataType.selectedItem.toString()
        val startDate = editTextStartDate.text.toString()
        val endDate = editTextEndDate.text.toString()
        
        if (startDate.isEmpty() || endDate.isEmpty()) {
            Toast.makeText(this, "请选择日期范围", Toast.LENGTH_SHORT).show()
            return
        }
        
        try {
            val csvContent = when (dataType) {
                "所有数据" -> exportAllData(startDate, endDate)
                "患者数据" -> exportPatientsData(startDate, endDate)
                "用户数据" -> exportUsersData()
                "科室数据" -> exportDepartmentsData()
                else -> ""
            }
            
            if (csvContent.isNotEmpty()) {
                val fileName = "${dataType}_${startDate}_${endDate}.csv"
                saveAndShareFile(csvContent, fileName)
            } else {
                Toast.makeText(this, "没有数据可导出", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "导出失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun exportAllData(startDate: String, endDate: String): String {
        val patients = databaseHelper.getPatientsByDateRange(startDate, endDate)
        val users = databaseHelper.getAllUsers()
        val departments = databaseHelper.getAllDepartments()
        
        val csvBuilder = StringBuilder()
        
        // 患者数据
        csvBuilder.append("=== 患者数据 ===\n")
        csvBuilder.append("姓名,性别,科室,入院日期,诊断,备注\n")
        patients.forEach { patient ->
            csvBuilder.append("${patient.name},${patient.gender},${patient.department},")
            csvBuilder.append("${patient.admissionDate},${patient.diagnosis},${patient.notes}\n")
        }
        csvBuilder.append("\n")
        
        // 用户数据
        csvBuilder.append("=== 用户数据 ===\n")
        csvBuilder.append("真实姓名,用户名,用户类型,科室,是否已批准,注册时间\n")
        users.forEach { user ->
            val userTypeText = when (user.userType) {
                UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                UserType.SUPER_ADMIN -> "总管理员"
                UserType.DEPARTMENT_ADMIN -> "科室管理员"
                UserType.USER -> "普通用户"
                else -> "未知角色"
            }
            csvBuilder.append("${user.realName},${user.username},$userTypeText,${user.department},${user.isApproved},${user.registrationDate}\n")
        }
        csvBuilder.append("\n")
        
        // 科室数据
        csvBuilder.append("=== 科室数据 ===\n")
        csvBuilder.append("科室名称,创建时间\n")
        departments.forEach { department ->
            csvBuilder.append("${department.name},${department.createdAt}\n")
        }
        
        return csvBuilder.toString()
    }
    
    private fun exportPatientsData(startDate: String, endDate: String): String {
        val patients = databaseHelper.getPatientsByDateRange(startDate, endDate)
        
        val csvBuilder = StringBuilder()
        csvBuilder.append("姓名,性别,科室,入院日期,诊断,备注\n")
        
        patients.forEach { patient ->
            csvBuilder.append("${patient.name},${patient.gender},${patient.department},")
            csvBuilder.append("${patient.admissionDate},${patient.diagnosis},${patient.notes}\n")
        }
        
        return csvBuilder.toString()
    }
    
    private fun exportUsersData(): String {
        val users = databaseHelper.getAllUsers()
        
        val csvBuilder = StringBuilder()
        csvBuilder.append("真实姓名,用户名,用户类型,科室,是否已批准,注册时间\n")
        
        users.forEach { user ->
            val userTypeText = when (user.userType) {
                UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                UserType.SUPER_ADMIN -> "总管理员"
                UserType.DEPARTMENT_ADMIN -> "科室管理员"
                UserType.USER -> "普通用户"
                else -> "未知角色"
            }
            csvBuilder.append("${user.realName},${user.username},$userTypeText,${user.department},${user.isApproved},${user.registrationDate}\n")
        }
        
        return csvBuilder.toString()
    }
    
    private fun exportDepartmentsData(): String {
        val departments = databaseHelper.getAllDepartments()
        
        val csvBuilder = StringBuilder()
        csvBuilder.append("科室名称,创建时间\n")
        
        departments.forEach { department ->
            csvBuilder.append("${department.name},${department.createdAt}\n")
        }
        
        return csvBuilder.toString()
    }
    
    private fun saveAndShareFile(content: String, fileName: String) {
        try {
            val downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            val file = File(downloadsDir, fileName)
            
            FileWriter(file).use { writer ->
                writer.write(content)
            }
            
            // 分享文件
            val uri = FileProvider.getUriForFile(
                this,
                "${packageName}.fileprovider",
                file
            )
            
            val shareIntent = Intent(Intent.ACTION_SEND).apply {
                type = "text/csv"
                putExtra(Intent.EXTRA_STREAM, uri)
                putExtra(Intent.EXTRA_SUBJECT, "数据导出")
                putExtra(Intent.EXTRA_TEXT, "导出的数据文件")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }
            
            startActivity(Intent.createChooser(shareIntent, "分享数据文件"))
            
            Toast.makeText(this, "数据已导出到: ${file.absolutePath}", Toast.LENGTH_LONG).show()
            
        } catch (e: Exception) {
            Toast.makeText(this, "保存文件失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            PermissionHelper.STORAGE_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    exportData()
                } else {
                    Toast.makeText(this, "需要存储权限才能导出数据", Toast.LENGTH_SHORT).show()
                }
            }
            PermissionHelper.NOTIFICATION_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "通知权限已授予", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "通知权限被拒绝，可能影响推送功能", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}